import "./index.scss";
import logo from "@/assets/logo.png";
import { Button, Form, Input, Card, message, notification } from "antd";
import { useDispatch } from "react-redux";
import { fetchLogin } from "@/store/modules/user";
import { useNavigate } from "react-router-dom";
import { SmileOutlined } from "@ant-design/icons";
import { useEffect } from "react";
import _ from "lodash";
function Login() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const onFinish = _.debounce(async (values) => {
    // fetchLogin：异步函数返回一个Promise
    await dispatch(fetchLogin(values));
    // 跳转到首页
    navigate("/");
    // 成功提示
    message.success("登录成功");
    notification.open({
      message: "欢迎回来",
      duration: 2,
      showProgress: true,
      icon: (
        <SmileOutlined
          style={{
            color: "#108ee9",
          }}
        />
      ),
    });
  }, 1000);
  useEffect(() => {
    // 更新页面标题
    document.title = "登录";
  }, []);
  return (
    <>
      <div className="login">
        <Card hoverable className="login-card">
          {/* logo */}
          <img className="login-logo" src={logo} alt="logo" />
          {/* 登录表单 */}
          {/* validateTrigger：表单校验触发时机 */}
          <Form
            validateTrigger={["onBlur", "onChange"]}
            initialValues={{ mobile: "13888888888", code: "246810" }}
            onFinish={onFinish}
          >
            <Form.Item
              name="mobile"
              // 设置多条校验规则
              rules={[
                {
                  required: true,
                  message: "请输入手机号!",
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: "请输入正确的手机号",
                },
              ]}
            >
              <Input size="large" placeholder="请输入手机号" />
            </Form.Item>
            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: "请输入验证码",
                },
                {
                  pattern: /^\d{6}$/,
                  message: "请输入6位数字验证码",
                },
              ]}
            >
              <Input size="large" placeholder="请输入验证码" />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                style={{ width: "100%" }}
                size="large"
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </>
  );
}

export default Login;
